package com.huitone.gddw.controller.worktable;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huitone.gddw.controller.common.CommonController;
import com.huitone.gddw.dao.entity.NetSwtich;
import com.huitone.gddw.dao.entity.SmLog;
import com.huitone.gddw.model.support.Message;
import com.huitone.gddw.model.support.QueryPage;
import com.huitone.gddw.service.INetSwtichService;
import com.huitone.gddw.service.dto.NetSwtichDTO;
import com.huitone.gddw.service.dto.monitoring.UnifyMonitorDTO;
import com.huitone.gddw.service.dto.monitoring.sms.AccessReportACDTO;
import com.huitone.gddw.service.monitoring.IUnifyMonitorService;
import com.huitone.gddw.service.monitoring.sms.IAccessReportService;
//import com.huitone.gddw.utils.MD5Util;
import com.huitone.gddw.utils.SysLoginUtil;
//import com.huitone.smspfm.redis.impl.HashOpts;
//import com.sun.tools.corba.se.idl.constExpr.And;

/**
 * 短信平台切换日志 控制器
 * @author wuluodan
 *
 */
@Controller
@RequestMapping(value="netSwtich")
public class NetSwtichController extends CommonController {
	private final static Logger LOGGER = Logger.getLogger(NetSwtichController.class);
	
	@Autowired
	private INetSwtichService netSwtichService;
	@Autowired
	private IAccessReportService accessReportService;
	
	@Autowired
	private IUnifyMonitorService unifyMonitorService;
	
	/**
	 * 通过平台id 名称查询
	 * @param page
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="queryIdOrName")
	public QueryPage<NetSwtichDTO> queryIdOrName(QueryPage<NetSwtich> page, HttpServletRequest request) {
		super.logType = SmLog.LOGTYPE_SELECT;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]查询短信平台切换";
		Map<String, Object> params = new HashMap<String, Object>();
		String srvId = request.getParameter("srvId");
		String srvName = request.getParameter("srvName");
		if(srvId != null)
		{
			params.put("srvId", srvId);
		}
		if(srvName != null)
		{
			params.put("srvName", srvName);
		}
		
		page.setParams(params);
		QueryPage<NetSwtichDTO> result = null;
		List<NetSwtichDTO> netDto = null;
		try {
			result = netSwtichService.findTerracePage(page);
			netDto = result.getResult();
			int i = 0;
			for(;i <=netDto.size()-1;i++)
			{
				netDto.get(i).setRuningFlag((netDto.get(i).getRuningFlag().equals("1"))?"新平台":"旧平台");
			}
		} catch (Exception e) {
			LOGGER.error("查询平台出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return result;
	}
	
	
	@ResponseBody
	@RequestMapping(value="smPlatInfo",method=RequestMethod.GET)
	public Map<String,Object> querySmSvrStatus(QueryPage page, HttpServletRequest request){
		super.logType = SmLog.LOGTYPE_SELECT;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]查询短信平台状态";
		
		long currentTimeMillis = System.currentTimeMillis(); 
		//获取上5分钟新指标
		CountDownLatch countDownLatch = new CountDownLatch(1);
		Map<String, Object> newHash = accessReportService.getNewIndicator(countDownLatch);
		
		
		page.setPageSize(100);
		QueryPage<NetSwtichDTO> queryPage = netSwtichService.findTerracePage(page);
		List<NetSwtichDTO> result = queryPage.getResult();
		boolean flag = true;
		for(NetSwtichDTO nst:result){
			
			flag = flag && "1".equals(nst.getStatus());
			
		}
		Map<String, Object> params = new HashMap<String, Object>();
		long timeMillis = System.currentTimeMillis();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		String date = sf.format(timeMillis);
		params.put("startDate", date);
		params.put("endDate", date);
		AccessReportACDTO find = accessReportService.find(params);
		
		Map<String, Object> param = new HashMap<>();
		param.put("startDate", (int)(timeMillis/1000)-10-10);
		param.put("endDate", (int)(timeMillis/1000));
		param.put("interval", 10);
		
		List<UnifyMonitorDTO> listPri = unifyMonitorService.findPri(param);
		List<UnifyMonitorDTO> list = getResult((int)(timeMillis/1000)-10,(int)(timeMillis/1000), 10, listPri);
		
		
		HashMap<String,Object> map = new HashMap<String,Object>();
		map.put("status", flag==true?"1":"0");
		map.put("sentedCount",find.getTotalCount());
		map.put("sendRate",find.getPeakRateCount());
		  sf = new SimpleDateFormat("yyyy-MM-dd");
		  date = sf.format(timeMillis- DateUtils.MILLIS_PER_HOUR);
		params.put("startDate", date);
//		map.put("sendTimeoutCount", accessReportService.find(params).getSendFailCount()); //更改指标周期调整
		map.put("QueueBlockingCount",find.getRecvNoneCount());

		if(list.size()==0){
			map.put("dueOutCount",0);
			
		}else{
			if (list.get(list.size()-1).getValueInt()==null ||list.get(list.size()-1).getValue().equals("0")) {
					map.put("dueOutCount",Float.valueOf(list.get(list.size()-2).getValue()));
			}else{
				map.put("dueOutCount",Float.valueOf(list.get(list.size()-1).getValue()));
			}
		}
		
		try {
			//等待所有线程执行完
			countDownLatch.await();
			//合并新增的指标数据：上5分钟的发送超时短信数量，上5分钟的报文发送成功数，上5分钟的报文发送成功数率
			map.put("sendTimeoutCount", newHash.get("sendTimeoutCount"));
			map.put("successfulCount", newHash.get("successfulCount"));
			map.put("successfulRate", newHash.get("successfulRate"));
		} catch (InterruptedException e) {
			LOGGER.error("等待所有线程执行完，出现异常：" + e.getMessage(), e);
		}
		LOGGER.info("*获取指标整个接口任务耗时："+(System.currentTimeMillis() - currentTimeMillis) );
		return map;
		
	}
	
	
	
	private List<UnifyMonitorDTO> getResult(Integer startDate, Integer endDate, Integer interval, List<UnifyMonitorDTO> result) {
		List<UnifyMonitorDTO> list = new ArrayList<>();
		int stime = startDate - interval;
		int etime = stime + interval;
		int j = 0;
		while (etime < endDate) {
			float data = 0;
			if (j > 0) {
				stime = etime;
				etime = stime + interval;
			}
			int i = 0;
			UnifyMonitorDTO um = new UnifyMonitorDTO();
			Iterator<UnifyMonitorDTO> it = result.iterator();
			boolean b = false;
			while (it.hasNext()) {
				um = it.next();
				if (um.getClock() != null && um.getClock() >= stime && um.getClock() < etime) {
					if (0 == i) {
						list.add(um);
						b = true;
					}
					data += Float.parseFloat(um.getValue());
					it.remove();
					i++;
				}
			}
			if (!b) {
				UnifyMonitorDTO e = new UnifyMonitorDTO();
				e.setValue("0");
				e.setClock(etime);
				e.setClockTime(new Date((long)(etime) * 1000));
				e.setKey(um.getKey());
				list.add(e);
			} else if (list != null && list.size() > 0 && b) {
				list.get(list.size() - 1).setValue(String.valueOf(data));
				list.get(list.size() - 1).setClockTime(new Date((long)(etime - 60) * 1000));
			}
			j++;
		}
		Collections.reverse(list);
		
		convert(list);
		
		return list;
	}
	
	
	/**
	 * 判断是否需要转换单位
	 * @param list
	 */
	private void convert(List<UnifyMonitorDTO> list) {
		// 以最大数判断显示单位
		boolean isW = false;
		for (UnifyMonitorDTO unifyMonitorDTO : list) {
			if (StringUtils.isNotBlank(unifyMonitorDTO.getValue()) && Float.valueOf(unifyMonitorDTO.getValue()) >= 10000f) {
				isW = true;
				break;
			}
		}
		
		// 判断是否转换数字
		if (isW) {
			for (UnifyMonitorDTO unifyMonitorDTO : list) {
				unifyMonitorDTO.setUnits("1");
				unifyMonitorDTO.setValue(StringUtils.isBlank(unifyMonitorDTO.getValue()) ? "" 
						: String.format("%.2f", Float.valueOf(unifyMonitorDTO.getValue()) / 10000f));
			}
		}
	}
	

	
	
	
	/**
	 * 更改线路类型
	 * @param srvId 记录ID
	 * @param terrace 更改后线路类型
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="changeTerrace")
	public Message changeTerrace(String pwd) {
		try {
			//pwd = MD5Util.encode(pwd);
			String  runStatus = netSwtichService.selectStatus();
			String runType = null;
			if(!runStatus.isEmpty())
			{
				if(runStatus.equals("1"))
				{
					runType = "2";
				}else
				{
					runType = "1";
				}
			}
			if (!pwd.equals(SysLoginUtil.getLoginUser().getPwd())) {
				return new Message(false, "密码不正确！");
			}
			netSwtichService.changeTerrace(runType);
			return new Message(true, "操作成功！");
		} catch (Exception e) {
			LOGGER.error("更改线路类型过程中出现异常：" + e.getMessage(), e);
			return new Message(false, "操作失败！");
		}
	}
	
}
